package com.lijianan.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lijianan.entity.Booking;
import com.lijianan.entity.MeetingRoom;
import com.lijianan.mapper.BookingMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BookingServiceImpl implements BookingService {

    @Autowired
    private BookingMapper bookingsMapper;

    @Autowired
    private MeetingRoomServiceImpl meetingRoomServiceImpl;

    @Autowired
    private BookingEquipmentServiceImpl bookingEquipmentServiceImpl;

    @Override
    public List<Booking> selectAll() {
        checkPaymentTimeout();
        return bookingsMapper.selectList(null);
    }

    @Override
    public Booking selectByBookingId(Integer booking_id) {
        checkPaymentTimeout();
        return bookingsMapper.selectById(booking_id);
    }

    @Override
    public List<Booking> selectByRoomId(Integer room_id) {
        checkPaymentTimeout();
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("room_id", room_id);
        return bookingsMapper.selectList(queryWrapper);
    }

    @Override
    public List<Booking> selectByCustomerId(Integer customer_id) {
        checkPaymentTimeout();
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", customer_id);
        return bookingsMapper.selectList(queryWrapper);
    }

    @Override
    public List<Booking> selectByStatusForPending() {
        checkPaymentTimeout();
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "pending_payment");
        return bookingsMapper.selectList(queryWrapper);
    }

    @Override
    public List<Booking> selectByStatusForConfirmed() {
        checkPaymentTimeout();
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "confirmed");
        return bookingsMapper.selectList(queryWrapper);
    }

    @Override
    public List<Booking> selectByCancelPending() {
        checkPaymentTimeout();
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cancellation_status", "pending");
        return bookingsMapper.selectList(queryWrapper);
    }

    @Override
    public boolean addBooking(Integer customer_id, Integer room_id, Date use_time_start
            , Date use_time_end, Integer attendee_count, Double price_per_hour, List<String> equipments) {
        MeetingRoom meetingRoom = meetingRoomServiceImpl.selectByRoomId(room_id);
        if (!"空闲".equals(meetingRoom.getCurrent_status())) {
            System.out.println("该会议室不是空闲的！");
            return false;
        }
        Booking booking = new Booking();
        booking.setCustomer_id(customer_id);
        booking.setRoom_id(room_id);
        booking.setUse_time_start(use_time_start);
        booking.setUse_time_end(use_time_end);
        booking.setAttendee_count(attendee_count);
        booking.setPrice_per_hour(price_per_hour);
        booking.setStatus("pending_payment");

        long timeDifference = use_time_end.getTime() - use_time_start.getTime();
        long hoursDifference = timeDifference / (60 * 60 * 1000);
        double amount = hoursDifference * price_per_hour;

        booking.setAmount(amount);
        int insert = bookingsMapper.insert(booking);
        if (insert == 0) {
            System.out.println("预定会议室失败！");
            return false;
        }

        for (String equipment : equipments)
            bookingEquipmentServiceImpl.updateBookingEquipment(booking.getBooking_id(), equipment);

        return meetingRoomServiceImpl.changeStatusToLock(room_id);
    }

    @Override
    public void checkPaymentTimeout() {
        List<Booking> bookings = bookingsMapper.selectList(null);
        for (Booking booking : bookings) {
            Date date = new Date();
            Date createdAt = booking.getCreated_at();
            long timeDifference = date.getTime() - createdAt.getTime();
            long minutesDifference = timeDifference / (60 * 1000);
            if (minutesDifference > 30 && booking.getStatus().equals("pending_payment")) {
                booking.setStatus("expired");
                bookingsMapper.updateById(booking);
                meetingRoomServiceImpl.changeStatusToFree(booking.getRoom_id());
            }
        }
    }

    @Override
    public boolean payment(Integer booking_id) {
        Booking booking = selectByBookingId(booking_id);
        MeetingRoom meetingRoom = meetingRoomServiceImpl.selectByRoomId(booking.getRoom_id());
        if ("pending_payment".equals(booking.getStatus()) && "锁定".equals(meetingRoom.getCurrent_status())) {
            booking.setPayment_time(new Date());
            booking.setStatus("confirmed");
            int update = bookingsMapper.updateById(booking);
            if (update == 0) {
                System.out.println("支付失败！");
                return false;
            }
            boolean changed = meetingRoomServiceImpl.changeStatusToSchedule(booking.getRoom_id());
            if (!changed) {
                System.out.println("会议室状态修改失败，支付失败！");
                return false;
            }
            System.out.println("已支付" + booking.getAmount());
            return true;
        }
        return false;
    }

    @Override
    public boolean changeStatusToPending(Integer booking_id) {
        Booking booking = selectByBookingId(booking_id);
        if (booking == null) {
            System.out.println("该预定不存在！");
            return false;
        }
        booking.setStatus("pending_payment");
        return bookingsMapper.updateById(booking) != 0;
    }

    @Override
    public boolean changeStatusToConfirmed(Integer booking_id) {
        Booking booking = selectByBookingId(booking_id);
        if (booking == null) {
            System.out.println("该预定不存在！");
            return false;
        }
        booking.setStatus("confirmed");
        return bookingsMapper.updateById(booking) != 0;
    }

    @Override
    public boolean changeStatusToCancelled(Integer booking_id) {
        Booking booking = selectByBookingId(booking_id);
        if (booking == null) {
            System.out.println("该预定不存在！");
            return false;
        }
        booking.setStatus("cancelled");
        return bookingsMapper.updateById(booking) != 0;
    }

    @Override
    public boolean changeStatusToExpired(Integer booking_id) {
        Booking booking = selectByBookingId(booking_id);
        if (booking == null) {
            System.out.println("该预定不存在！");
            return false;
        }
        booking.setStatus("expired");
        return bookingsMapper.updateById(booking) != 0;
    }

    @Override
    public boolean changeStatusToCompleted(Integer booking_id) {
        Booking booking = selectByBookingId(booking_id);
        if (booking == null) {
            System.out.println("该预定不存在！");
            return false;
        }
        booking.setStatus("completed");
        return bookingsMapper.updateById(booking) != 0;
    }

    @Override
    public boolean changeCancelStatusToApproved(Integer booking_id, Integer user_id) {
        Booking booking = selectByBookingId(booking_id);
        if (booking == null) {
            System.out.println("该预定不存在！");
            return false;
        }
        booking.setCancellation_status("approved");
        booking.setCancellation_processed_by(user_id);
        booking.setCancellation_processed_at(new Date());
        return bookingsMapper.updateById(booking) != 0;
    }

    @Override
    public boolean changeCancelStatusToRejected(Integer booking_id, Integer user_id) {
        Booking booking = selectByBookingId(booking_id);
        if (booking == null) {
            System.out.println("该预定不存在！");
            return false;
        }
        booking.setCancellation_status("rejected");
        booking.setCancellation_processed_by(user_id);
        booking.setCancellation_processed_at(new Date());
        return bookingsMapper.updateById(booking) != 0;
    }

    @Override
    public boolean judgeRoomCanCancel(Booking booking) {
        MeetingRoom meetingRoom = meetingRoomServiceImpl.selectByRoomId(booking.getRoom_id());
        if (!"confirmed".equals(booking.getStatus()) || !"预定".equals(meetingRoom.getCurrent_status())) {
            return false;
        }
        Date useTimeStart = booking.getUse_time_start();
        Date date = new Date();
        long timeDifference = useTimeStart.getTime() - date.getTime();
        long hoursDifference = timeDifference / (60 * 60 * 1000);
        if (hoursDifference > 24) {
            if (hoursDifference > 72) {
                booking.setRefund_percentage(100);
                booking.setRefund_amount(booking.getAmount());
                bookingsMapper.updateById(booking);
            } else if (hoursDifference > 48) {
                booking.setRefund_percentage(75);
                booking.setRefund_amount(booking.getAmount() * 0.75);
                bookingsMapper.updateById(booking);
            } else {
                booking.setRefund_percentage(25);
                booking.setRefund_amount(booking.getAmount() * 0.25);
                bookingsMapper.updateById(booking);
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean judgeBookingCanComplete(Booking booking) {
        if (booking == null)
            return false;
        MeetingRoom meetingRoom = meetingRoomServiceImpl.selectByRoomId(booking.getRoom_id());
        return "confirmed".equals(booking.getStatus()) && "使用".equals(meetingRoom.getCurrent_status());
    }

    @Override
    public List<Booking> selectByCancelStatusForPending() {
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cancellation_status", "pending");
        return bookingsMapper.selectList(queryWrapper);
    }

    @Override
    public List<Booking> selectByCancelStatusForApprove() {
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cancellation_status", "approved");
        return bookingsMapper.selectList(queryWrapper);
    }

    @Override
    public boolean submitCancelReservation(Integer customer_id, Integer room_id) {
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", customer_id).eq("room_id", room_id).eq("status","confirmed").isNull("cancellation_status");
        Booking booking = bookingsMapper.selectOne(queryWrapper);

        booking.setCancellation_requested_at(new Date());
        booking.setCancellation_status("pending");
        return bookingsMapper.updateById(booking) != 0;
    }

    @Override
    public boolean confirmCancelSuccess(Integer booking_id) {
        System.out.println("confirmCancelSuccess" + booking_id);
        Booking booking = selectByBookingId(booking_id);
        System.out.println("客户" + booking.getCustomer_id() + "获取退款：" + booking.getRefund_amount());
        return meetingRoomServiceImpl.changeStatusToFree(booking.getRoom_id()) && changeStatusToCancelled(booking_id);
    }
}
